package cn.hongxin.sap.conn.config;

import cn.hongxin.sap.conn.constants.CommonFieldEnum;
import cn.getech.poros.framework.common.bean.UserBaseInfo;
import cn.getech.poros.framework.common.context.PorosContextHolder;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Arrays;
import java.util.Date;
import java.util.TimeZone;

/**
 * @author hengji.li@getech.cn
 * @date 2020/2/19
 */
@EnableTransactionManagement
@Configuration
@MapperScan({"cn.hongxin.sap.conn.**.mapper", "cn.hongxin.busi.online.**.mapper"})
public class MybatisPlusConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }

    @Bean
    public GlobalConfig globalConfig() {
        return new GlobalConfig().setMetaObjectHandler(metaHandler());
    }

    @Bean
    public MetaObjectHandler metaHandler(){
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                UserBaseInfo currUser = PorosContextHolder.getCurrentUser();
                this.setFieldValByName(CommonFieldEnum.CREATE_TIME.getFiled(), new Date(), metaObject);
                this.setFieldValByName(CommonFieldEnum.CREATE_BY.getFiled(), currUser.getUid(), metaObject);
                this.setFieldValByName(CommonFieldEnum.UPDATE_TIME.getFiled(), new Date(), metaObject);
                this.setFieldValByName(CommonFieldEnum.UPDATE_BY.getFiled(), currUser.getUid(), metaObject);
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                UserBaseInfo currUser = PorosContextHolder.getCurrentUser();
                this.setFieldValByName(CommonFieldEnum.UPDATE_BY.getFiled(), currUser.getUid(), metaObject);
            }
        };
    }
}
